﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class FormPackages : Form
    {

        public FormPackages()
        {
            InitializeComponent();
        }


        /// Validation of the input information

        SqlConnection myConn = new SqlConnection("server=(local);database=TravelExperts;integrated security=SSPI");

        private bool validateData()
        {
            //Packages myPackage = new Packages();

            if (double.Parse(txtAgencyComm.Text) > double.Parse(txtPkgPrice.Text))
            {
                MessageBox.Show("Agency commision can not be greater than the base price");
                return false;
            }

            if (dtpPkgStart.Value > dtpPkgEnd.Value)
            {
                MessageBox.Show(" End of Package date can not be later than the start of Package date");
                return false;
            }

            if (txtPkgName.Text == "")
            {
                MessageBox.Show("Package name can not be null");
                return false;
            }

            if (txtPkgDescription.Text == "")
            {
                MessageBox.Show("Description can not be null");
                return false;
            }

            return true;

        }

        ///Get all the information for insert into database

        private Packages PackageDetails()
        {
            Packages myPackage = new Packages();
            if (validateData())
            {
                myPackage.PackageId = int.Parse(txtPkgId.Text);
                myPackage.PkgName = txtPkgName.Text;
                myPackage.PkgStartDate = dtpPkgStart.Value;
                myPackage.PkgEndDate = dtpPkgEnd.Value;
                myPackage.PkgBasePrice = decimal.Parse(txtPkgPrice.Text);
                myPackage.PkgDesc = txtPkgDescription.Text;
                myPackage.PkgAgencyCommission = decimal.Parse(txtAgencyComm.Text);
            }

            return myPackage;
        }
        ////////////////////  end of validation and package details/////////////////////////////
        private void eXITToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        ////////////////////exit application////////////////////////////////////////////////////

        private void PopulateCmb()
        {
            //Added by: Moses
            //Added on: 2012/01/20

            //function that populates the search field comboboxes with values from
            //Products and Suppliers tables

            //clear all comboboxes first
            foreach (Control ctrl in grpProducts.Controls)
            {
                if (ctrl.GetType() == typeof(ComboBox))
                    { ((ComboBox)ctrl).Items.Clear(); }
            }

            //get products and suppliers
            List<Products> products = new DbAccess().SelectProducts();
            List<Suppliers> suppliers = new DbAccess().SelectSuppliers();

            //add an option for "ALL" (no filtering)
            this.cmbSearchProducts.Items.Add("ALL");
            this.cmbSearchSuppliers.Items.Add("ALL");
            
            //add the entries to the combobox
            foreach (Products entry in products)
                { this.cmbSearchProducts.Items.Add(entry); }

            foreach (Suppliers entry in suppliers)
                { this.cmbSearchSuppliers.Items.Add(entry); }

            //populate the selected search parameter
            this.cmbSearchSelected.Items.Add("ALL");
            this.cmbSearchSelected.Items.Add("YES");
            this.cmbSearchSelected.Items.Add("NO");

        }

        private void resetPkgInfoPane()
        {
            //Added by: Moses
            //Added on: 2012/01/20

            foreach (Control ctrl in gpbPackages.Controls)
            {
                //clear all textboxes
                if (ctrl.GetType() == typeof(TextBox))
                    { ctrl.Text = ""; }

                //set all datetimepickers to today's date
                if (ctrl.GetType() == typeof(DateTimePicker))
                    { ((DateTimePicker)ctrl).Value = DateTime.Today; }

                //set all comboboxes selectedindex to 0
                if (ctrl.GetType() == typeof(GroupBox))
                {
                    foreach (Control gpbCtrl in ((GroupBox)ctrl).Controls)
                    {
                        if (gpbCtrl.GetType() == typeof(ComboBox))
                            { ((ComboBox)gpbCtrl).SelectedIndex = 0; }
                    }
                }
            }

            txtPkgId.Enabled = false;
            txtPkgId.Text = 0 + "";

            //fill checkedlistbox with all available products from productsSuppliers table
            List<ProductsSuppliers> proSupList = new DbAccess().SelectProductsSuppliers();

            foreach (ProductsSuppliers entry in proSupList)
                { clbProdSups.Items.Add(entry, false); }

        }

        private void refreshPkgListPane()
        {
            //Added by: Moses
            //Added on: 2012/01/20
            
            //clear the listbox and populate with all packages
            lstDisplay.Items.Clear();
            lstDisplay.Items.Add("CREATE NEW PACKAGE");
            lstDisplay.Items.Add("");
            List<Packages> pkgList = new DbAccess().SelectPackages();

            foreach (Packages entry in pkgList)
                { lstDisplay.Items.Add(entry); }

        }

        private void FormPackages_Load(object sender, EventArgs e)
        {
            //Added by: Moses
            //Added on: 2012/01/20

            PopulateCmb();
            resetPkgInfoPane();
            refreshPkgListPane();
            showPkgList();
        }

        private void cmbSearchSuppliers_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Added by: Moses
            //Added on: 2012/01/20
            //Edited on: 2012/01/21 -- added default checks to products when a package has been selected

            List<ProductsSuppliers> searchResults = new Search().filterProSup(this);
            List<PackagesProductsSupplier> ppsList = new DbAccess().SelectPackagesProSupp();

            clbProdSups.Items.Clear();
            foreach (ProductsSuppliers entry in searchResults)
            {clbProdSups.Items.Add(entry, false);}
            
            
        }

        private void cmbSearchProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Added by: Moses
            //Added on: 2012/01/20
            //Edited on: 2012/01/21 -- added default checks to products when a package has been selected

            List<ProductsSuppliers> searchResults = new Search().filterProSup(this);
            List<PackagesProductsSupplier> ppsList = new DbAccess().SelectPackagesProSupp();

            clbProdSups.Items.Clear();
            foreach (ProductsSuppliers entry in searchResults)
            { clbProdSups.Items.Add(entry, false); }
        }

        private void showPkgDeets()
        {
            //Added by: Moses
            //Added on: 2012/01/21

            //show the package edit groupbox and hide the package list groupbox
            gpbPkgList.Visible = false;
            gpbPkgList.Enabled = false;
            gpbPackages.Visible = true;
            gpbPackages.Enabled = true;
        }

        private void showPkgList()
        {
            //Added by: Moses
            //Added on: 2012/01/21

            //show the package list groupbox and hide package edit groupbox
            gpbPackages.Visible = false;
            gpbPackages.Enabled = false;
            gpbPkgList.Visible = true;
            gpbPkgList.Enabled = true;
        }

        private void lstDisplay_Click(object sender, EventArgs e)
        {
            //Added by: Moses
            //Added on: 2012/01/21

            //3 types of objects stored in this listbox
            //strings, nulls, and packages
            //nulls are only used to format
            //strings are commands or package details

            if (lstDisplay.SelectedItem != null)
            {

                if ((lstDisplay.SelectedItem).GetType() == typeof(string))
                {
                    switch ((lstDisplay.SelectedItem).ToString())
                    {
                        //take care of any commands here
                        case "CREATE NEW PACKAGE":
                            //go to package details pane
                            btnMultiFunc.Text = "SAVE NEW";
                            btnClear.Text = "CLEAR FORM";
                            resetPkgInfoPane();
                            showPkgDeets();
                            break;

                        case "BACK TO ALL PACKAGES":
                            refreshPkgListPane();
                            break;


                        case "EDIT THIS PACKAGE":
                            //go to package details pane
                            //and populate fields with selected package

                            //ensure the first item is in fact a Package
                            if (lstDisplay.Items[0].GetType() == typeof(Packages))
                            {
                                btnMultiFunc.Text = "UPDATE RECORD";
                                btnClear.Text = "CREATE NEW";

                                Packages pkg = (Packages)lstDisplay.Items[0];
                                txtPkgId.Text = pkg.PackageId + "";
                                txtPkgName.Text = pkg.PkgName;
                                dtpPkgStart.Value = pkg.PkgStartDate;
                                dtpPkgEnd.Value = pkg.PkgEndDate;
                                txtPkgDescription.Text = pkg.PkgDesc;
                                txtPkgPrice.Text = pkg.PkgBasePrice.ToString("F2");
                                txtAgencyComm.Text = pkg.PkgAgencyCommission.ToString("F2");

                                showPkgDeets();
                            }

                            break;

                        case "DELETE THIS PACKAGE":

                            //ensure the first item is a Package
                            if (lstDisplay.Items[0].GetType() == typeof(Packages))
                            {
                                Packages pkg = (Packages)lstDisplay.Items[0];

                                //show a msg box to confirm deletion
                                DialogResult confirm = MessageBox.Show("Do you really want to delete " + pkg.PkgName + "?",
                                    "Confirm Package Deletion", MessageBoxButtons.YesNo);

                                if (confirm == DialogResult.Yes)
                                {
                                    new DbAccess().DeletePackages(pkg);
                                    refreshPkgListPane();
                                }
                            }

                            else
                            { MessageBox.Show("Could not delete!\nUnknown error!"); }



                            break;



                        default:
                            break;

                    }
                }

                else if ((lstDisplay.SelectedItem).GetType() == typeof(Packages))
                {
                    Packages selected = (Packages)lstDisplay.SelectedItem;
                    //a package has been selected
                    //show package details in listbox,
                    //followed by EDIT, DELETE, BACK commands
                    lstDisplay.Items.Clear();

                    lstDisplay.Items.Add(selected);
                    lstDisplay.Items.Add("\tID: " + selected.PackageId);
                    lstDisplay.Items.Add("\tNAME: " + selected.PkgName);
                    lstDisplay.Items.Add("\tDESCRIPTION: " + selected.PkgDesc);
                    lstDisplay.Items.Add("");
                    lstDisplay.Items.Add("DATES");
                    lstDisplay.Items.Add("\tSTART: " + selected.PkgStartDate.ToString("yyyy/MM/dd"));
                    lstDisplay.Items.Add("\tEND: " + selected.PkgEndDate.ToString("yyyy/MM/dd"));
                    lstDisplay.Items.Add("");
                    lstDisplay.Items.Add("PRICING");
                    lstDisplay.Items.Add("\tBASE: " + selected.PkgBasePrice.ToString("C"));
                    lstDisplay.Items.Add("\tCOMMISSION: " + selected.PkgAgencyCommission.ToString("C"));
                    lstDisplay.Items.Add("");
                    lstDisplay.Items.Add("");

                    //add some commands

                    lstDisplay.Items.Add("EDIT THIS PACKAGE");
                    lstDisplay.Items.Add("DELETE THIS PACKAGE");
                    lstDisplay.Items.Add("BACK TO ALL PACKAGES");

                }


            }
        }

        private void btnShowPkgs_Click(object sender, EventArgs e)
        {
            //Added by: Moses
            //Added on: 2012/01/21

            refreshPkgListPane();
            showPkgList();
        }

        private void btnMultiFunc_Click(object sender, EventArgs e)
        {
            //Added by: Moses
            //Added on: 2012/01/21

            //this button will trigger an update or save a new package
            switch (btnMultiFunc.Text)
            {
                case "SAVE NEW":
                    Packages newCandidate = PackageDetails();
                    if (newCandidate != null)
                    { 
                        new DbAccess().InsertPackages(newCandidate);
                        refreshPkgListPane();
                        showPkgList();
                    }

                    else
                        { MessageBox.Show("Could not save new package.\nUnknown error!"); }

                    break;

                case "UPDATE RECORD":
                    Packages updCandidate = PackageDetails();
                    if (updCandidate != null)
                    { 
                        new DbAccess().UpdatePackages(updCandidate);
                        refreshPkgListPane();
                        showPkgList();
                    }

                    else
                        { MessageBox.Show("Could not update package.\nUnknown error!"); }

                    break;

                default: break;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            //Added by: Moses
            //Added on: 2012/01/21

            
            switch (btnClear.Text)
            {
                case "CLEAR FORM":
                    resetPkgInfoPane();
                    break;

                case "CREATE NEW":
                    resetPkgInfoPane();
                    btnMultiFunc.Text = "SAVE NEW";
                    break;

                default: break;
            }
            
        }


    }
}